//
//  VisitorLoginView.swift
//  Weibo007
//
//  Created by wuxl on 15/6/24.
//  Copyright © 2015年 heima. All rights reserved.
//

import UIKit

/// 访客视图协议 - 协议需要继承自 NSObjectProtocol
protocol VisitorLoginViewDelegate: NSObjectProtocol {
    func visitorRegisterButtonClicked()
    func visitorLoginButtonClicked()
}

class VisitorLoginView: UIView {

    ///   代理 weak id<VisitorLoginViewDelegate> delegate
    weak var delegate: VisitorLoginViewDelegate?
    
    
    // 视图的默认的构造方法
    // 创建控件，并且指定布局，用 xib & sb 开发不会调用
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    // 解档，用 xib & sb 开发会调用
    // mark - 为什么创建 override init(frame: CGRect) 方法一定要创建这个方法
    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // 创建控件
    private func setupUI() {
        // 1. 添加控件
        addSubview(iconView)
        addSubview(maskIconView)
        addSubview(homeIconView)
        addSubview(messageLabel)
        addSubview(registerButton)
        addSubview(loginButton)
        
        // 2. 自动布局
        iconView.translatesAutoresizingMaskIntoConstraints = false

        // 设置iconView约束
        addConstraint(NSLayoutConstraint(item: iconView, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.CenterX, multiplier: 1.0, constant: 0))
        addConstraint(NSLayoutConstraint(item: iconView, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.CenterY, multiplier: 1.0, constant: -40))
        // 设置homeIconView约束
        homeIconView.translatesAutoresizingMaskIntoConstraints = false
        addConstraint(NSLayoutConstraint(item: homeIconView, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: iconView, attribute: NSLayoutAttribute.CenterX, multiplier: 1.0, constant: 0))
        addConstraint(NSLayoutConstraint(item: homeIconView, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: iconView, attribute: NSLayoutAttribute.CenterY, multiplier: 1.0, constant: 0))
        // 设置messageLabel约束
        messageLabel.translatesAutoresizingMaskIntoConstraints = false
        addConstraint(NSLayoutConstraint(item: messageLabel, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: iconView, attribute: NSLayoutAttribute.CenterX, multiplier: 1.0, constant: 0))
        addConstraint(NSLayoutConstraint(item: messageLabel, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: iconView, attribute: NSLayoutAttribute.Bottom, multiplier: 1.0, constant: 20))
        // 开始通过 vfl(可视化格式语言) 来给messageLabel的宽高添加约束
        addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:[subView(240)]", options: NSLayoutFormatOptions.AlignAllBaseline, metrics: nil, views: ["subView": messageLabel]))
        addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[subView(40)]", options: NSLayoutFormatOptions.AlignAllBaseline, metrics: nil, views: ["subView" : messageLabel]))
        // 设置registerButton约束
        registerButton.translatesAutoresizingMaskIntoConstraints = false
        addConstraint(NSLayoutConstraint(item: registerButton, attribute: NSLayoutAttribute.Left, relatedBy: NSLayoutRelation.Equal, toItem: messageLabel, attribute: NSLayoutAttribute.Left, multiplier: 1.0, constant: 0))
        addConstraint(NSLayoutConstraint(item: registerButton, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: messageLabel, attribute: NSLayoutAttribute.Bottom, multiplier: 1.0, constant: 20))
        addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:[subView(100)]", options: NSLayoutFormatOptions.AlignAllBaseline, metrics: nil, views: ["subView" : registerButton]))
        addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[subView(40)]", options: NSLayoutFormatOptions.AlignAllBaseline, metrics: nil, views: ["subView" : registerButton]))
        // 设置loginButton约束
        loginButton.translatesAutoresizingMaskIntoConstraints = false
        addConstraint(NSLayoutConstraint(item: loginButton, attribute: NSLayoutAttribute.Right, relatedBy: NSLayoutRelation.Equal, toItem: messageLabel, attribute: NSLayoutAttribute.Right, multiplier: 1.0, constant: 0))
        addConstraint(NSLayoutConstraint(item: loginButton, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: messageLabel, attribute: NSLayoutAttribute.Bottom, multiplier:1.0, constant: 20))
        addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:[subView(100)]", options: NSLayoutFormatOptions.AlignAllBaseline, metrics: nil, views: ["subView" : loginButton]))
        addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[subView(40)]", options: NSLayoutFormatOptions.AlignAllBaseline, metrics: nil, views: ["subView" : loginButton ]))
        // 设置maskIconView的约束
        maskIconView.translatesAutoresizingMaskIntoConstraints = false
        addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[subView]|", options: NSLayoutFormatOptions.AlignAllBaseline, metrics: nil, views: ["subView" : maskIconView]))
        addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[subView]-160-|", options: NSLayoutFormatOptions.AlignAllBaseline, metrics: nil, views: ["subView" : maskIconView]))
        
        // 背景颜色 
        backgroundColor = UIColor(white: 237.0 / 255.0, alpha: 1.0)
    }
    
    ///  设置视图内容
    ///
    ///  :param: iconName 图标名称
    ///  :param: message  消息文本
    ///  :param: isHome   是否首页
    func setupViewInfo(iconName: String, message: String, isHome: Bool) {
        // 设置文本
        messageLabel.text = message
        
        if isHome {
            // 如果是主页，小房子显示，转轮显示
            homeIconView.hidden = false
            iconView.image = UIImage(named: "visitordiscover_feed_image_smallicon")
        } else {
            // 如果不是主页，小房子隐藏，转轮变成别的
            homeIconView.hidden = true
            iconView.image = UIImage(named: iconName)
            // 将视图层次置后
            sendSubviewToBack(maskIconView)
        }
    }
    
    // 测试变量
    var isPaused = false
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {

        isPaused ? resumeAnimation() : pauseAnimation()
        isPaused = !isPaused
    }
    
    /// 启动动画
    func startAnimation() {
        let anim = CABasicAnimation(keyPath: "transform.rotation")
        anim.toValue = 2 * M_PI
        anim.duration = 20
        anim.repeatCount = MAXFLOAT
        anim.removedOnCompletion = false
        iconView.layer.addAnimation(anim, forKey: nil)
    }
    
    /// 暂停动画
    func pauseAnimation() {
        // 设置动画属性
        // 1> 将速度设置为0，动画会停止，复位到初始的状态
        iconView.layer.speed = 0
        // 2> 设置时间偏移，将动屯田帧停止在当前的动画状态
        iconView.layer.timeOffset = CACurrentMediaTime()
    }
    
    /// 继续动画
    func resumeAnimation() {
        // 1> 恢复动画速度
        iconView.layer.speed = 1
        // 2> 动画的开始时间
        iconView.layer.beginTime = CACurrentMediaTime() - iconView.layer.timeOffset
        // 3> 恢复时间偏移
        iconView.layer.timeOffset = 0
    }
    
    // mark - 懒加载控件
    ///  图标
    lazy var iconView: UIImageView = {
        let image = UIImage(named: "visitordiscover_feed_image_smallicon")
        return UIImageView(image: image)
    }()
    
    ///  遮罩图片，不要写 'maskView'
    lazy var maskIconView: UIImageView = {
        let image = UIImage(named: "visitordiscover_feed_mask_smallicon")
        return UIImageView(image: image)
    }()

    ///  小房子图标
    lazy var homeIconView: UIImageView = {
        let image = UIImage(named: "visitordiscover_feed_image_house")
        return UIImageView(image: image)
    }()
    
    ///  文本标签
    lazy var messageLabel: UILabel = {
        // 一旦使用了自动布局，frame 就失效了
        let label = UILabel(frame: CGRectMake(0, 0, 240, 40))
        label.text = "登录后，最新、最热微博尽在掌握，不再会与实事潮流擦肩而过"
        label.textColor = UIColor.darkGrayColor()
        label.font = UIFont.systemFontOfSize(14)
        label.textAlignment = NSTextAlignment.Center
        label.preferredMaxLayoutWidth = 224
        // 最多两行，超出之后显示 '...'
        label.numberOfLines = 0
        label.sizeToFit()
        
        return label
    }()
    
    ///  注册按钮
    lazy var registerButton: UIButton = {
        let btn = UIButton(frame: CGRectMake(0, 0, 100, 40))
        
        btn.setTitle("注册", forState: UIControlState.Normal)
        btn.setTitleColor(UIColor.orangeColor(), forState: UIControlState.Normal)
        btn.setBackgroundImage(UIImage(named: "common_button_white_disable"), forState: UIControlState.Normal)
        btn.addTarget(self, action: "register", forControlEvents: UIControlEvents.TouchUpInside)
      
        return btn
    }()
    
    ///  登录按钮
    lazy var loginButton: UIButton = {
        let btn = UIButton(frame: CGRectMake(200, 220, 100, 40))
        
        btn.setTitle("登录", forState: UIControlState.Normal)
        btn.setTitleColor(UIColor.darkGrayColor(), forState: UIControlState.Normal)
        btn.setBackgroundImage(UIImage(named: "common_button_white_disable"), forState: UIControlState.Normal)
        btn.addTarget(self, action: "login", forControlEvents: UIControlEvents.TouchUpInside)
        
        return btn
    }()
    
    
    ///  用户注册
    func register() {
        delegate?.visitorRegisterButtonClicked()
    }
    
    ///  用户登录
    func login() {
        delegate?.visitorLoginButtonClicked()
    }
}
